package com.jrzh.security.authority;

import java.io.IOException;

import javax.servlet.*;

import org.apache.log4j.Logger;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
/**
 * 权限管理过滤器
 * 实时监控用户行为，防止用户访问未被授权的资源
 * @author Xanthin
 *
 */
public class CustomFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter{

	private static final Logger logger = Logger.getLogger(CustomFilterSecurityInterceptor.class);
	private FilterInvocationSecurityMetadataSource securityMetadataSource;
	
	public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
		return this.securityMetadataSource;
	}

	public void setSecurityMetadataSource(
			FilterInvocationSecurityMetadataSource securityMetadataSource) {
		this.securityMetadataSource = securityMetadataSource;
	}

	@Override
	public Class<?> getSecureObjectClass() {
		return FilterInvocation.class;
	}

	@Override
	public SecurityMetadataSource obtainSecurityMetadataSource() {
		return this.securityMetadataSource;
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
		FilterInvocation fi = new FilterInvocation(request, response,chain);
		logger.debug("====="+fi.getRequestUrl());
		invoke(fi);
	}
	
	public void invoke(FilterInvocation fi) throws IOException, ServletException{
		InterceptorStatusToken token = super.beforeInvocation(fi);
		try {
			fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally{
			super.afterInvocation(token, null);
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void destroy() {
	}

}
